package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 陈辉
 * @data 2023 11:24
 * 过滤器作用：实现全局的统一登录验证功能
 */
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 拿到请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2. 判断本次请求的是否是登录相关资源：是，则直接放行
        if(request.getURI().getPath().contains("/login")){
            return chain.filter(exchange);
        }

        try {
            //3. 不是登录，需要进行token验证
            //4. 先获取到token
            String token = request.getHeaders().getFirst("token");

            //5. 验证token是否有效：a.不能为空；b. 不能过期;c.解析不能出错；不通过统一返回：401
            if (StringUtils.isEmpty(token)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //Object appUserId = claimsBody.get("id");
            int res = AppJwtUtil.verifyToken(claimsBody);
            if (res == 1 || res == 2){
                //b. 不能过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //没过期：将token解析得到用户id，并且存入request的header头，转发给下游微服务
            Object userId = claimsBody.get("id");
            //在header中添加新的信息
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //6. 验证都通过了，就放行
        return chain.filter(exchange);
    }
}
